package com.keyidea.jfxui.core.config.redis;

import com.keyidea.jfxui.core.server.utils.ByteUtils;
import com.keyidea.jfxui.core.util.MemStorage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 功能描述：打印收到的Redis信息
 */
@Slf4j
public class PrintMessageListener implements MessageListener {

    private final StringRedisSerializer stringRedisSerializer;

    public PrintMessageListener(StringRedisSerializer stringRedisSerializer) {
        this.stringRedisSerializer = stringRedisSerializer;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = stringRedisSerializer.deserialize(message.getChannel());
        handleMessage(channel, message.getBody());
    }

    private void handleMessage(String channel, byte[] body) {
        try {
            String hexStr = ByteUtils.bytesToHex(body);
            MemStorage.REDIS_MESSAGE_LIST.add(String.format("频道[%s]<<<%s %n", channel, hexStr));
            log.info("PrintMessageListener {} 队列，收到字节消息:{}", channel, body);
            log.info("PrintMessageListener {} 队列，收到十六进制字节消息:{}", channel, hexStr);
//            // 空口协议 回显
//            MemStorage.AIR_MESSAGE_LIST.add(MessageViewEntity.of(hexStr, Constants.MESSAGE_TYPE_TO));
//            // channel格式“卫星:波束:反向频点”，通过截取获得反向频点，再由反向频点获取ip
//            String[] split = channel.split(":");
//            if (split.length == 3) {
//                BackwardFp backwardFp = MemStorage.BACKWARD_FD_IP_MAP.get(Long.parseLong(split[2]));
//                log.warn("backwardFp--------------------" + backwardFp.toString());
//                // 通过ip获取socket
//                DatagramSocket datagramSocket = MemStorage.AIR_IP_SOCKET_MAP.get(backwardFp.getIp());
//                // 通过socket发送消息到网控
//                UdpClient.sendMsg(datagramSocket, MemStorage.GLOBAL_HM_CONFIG.getSatIp(), MemStorage.GLOBAL_HM_CONFIG.getSatAirPort(), body);
//            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
